<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/3/25 0025
 * Time: 16:33
 */

namespace app\api\service;


use app\service\BaseService;
use think\Db;

class TimePlanService extends BaseService
{
    /**
     * @name 分享奖（直推算力 )
     * @author zay
     * @Date 2020/3/25 0025 17:37
     */
    public function fenxiang()
    {
        //查询邀请人数大于10的
        $list = Db('user')->field('tname,tid,count(*) as count,sum(power) as power,uname')
            ->where(['is_effect' => 1])
            ->where('tid', '>', 0)
            ->group('tid')
            /* ->having('count(*)>=10')*/
            ->select();
        //获取矿机信息
        $kj_list = DB('shop_project')->column('name,price,imagepath,yxzq,kjsl,capacity', 'id');
        //获取佣金设置
        $share_reward = setting('share_reward');
        $share_reward = json_decode($share_reward, true);
        $share_reward = $share_reward ? $share_reward : [];
        if (empty($share_reward)) {
            echo "未设置分享奖励";
            exit;
        }
        //每次记录奖励设置数据
        Db('setting_log')->insert(['content'=>setting('share_reward'),'time'=>time()]);
        foreach ($list as $k => &$v) {
            //查询该用户直推多少人
            /*$zt_num = Db('user')->field('count(*) as count')->where(['is_effect' => 1, 'tid' => $v['tid']])->find();
            $zt_num = !empty($zt_num['count']) ? $zt_num['count'] : 0;
            $v['count'] = $zt_num;*/
            $types = [];
            if ($v['count'] >= $share_reward[0]['num'] && $v['power'] >= $share_reward[0]['power']) {//邀请10人算力5G送一台微矿
                //
                $types[] = $share_reward[0]['kj_id'];
            }
            if ($v['count'] >= $share_reward[1]['num'] && $v['power'] >= $share_reward[1]['power']) {//邀请20人算力20G送小矿一台
                $types[] = $share_reward[1]['kj_id'];
            }
            if ($v['count'] >= $share_reward[2]['num'] && $v['power'] >= $share_reward[2]['power']) {//邀请40人算力100G送中矿一台
                $types[] = $share_reward[2]['kj_id'];
            }
            if ($v['count'] >= $share_reward[3]['num'] && $v['power'] >= $share_reward[3]['power']) {//邀请80人算力300G送大矿一台
                $types[] = $share_reward[3]['kj_id'];
            }
            if ($v['count'] >= $share_reward[4]['num'] && $v['power'] >= $share_reward[4]['power']) {//邀请160人算力650G送超矿一台
                $types[] = $share_reward[4]['kj_id'];
            }
            foreach ($types as $key => $type) {
                $insert_data = [
                    'mobile' => $v['tname'],
                    'project' => $kj_list[$type]['name'],
                    'addtime' => time(),
                    'zt' => 0,
                    'imagepath' => $kj_list[$type]['imagepath'],
                    'yxzq' => $kj_list[$type]['yxzq'],
                    'price' => $kj_list[$type]['price'],
                    'kjsl' => $kj_list[$type]['kjsl'],
                    'kjbh' => orderSn(),
                    'uid' => $v['tid'],
                    'capacity' => $kj_list[$type]['capacity'],
                    'type' => 1,
                    'kj_type' => $type
                ];
                //查询用户是否已经送过
                $kj_info = DB('shop_orderform')->where(['type' => 1, 'kj_type' => $type, 'uid' => $v['tid']])->find();
                if (empty($kj_info)) {
                    Db('shop_orderform')->insert($insert_data);
                }
            }
        }
        echo "分享奖励发放完毕";
    }

    /**
     * @name 邀请奖励币每天释放
     * @author zay
     * @Date 2020/3/26 0026 11:59
     */

    public function release_coin()
    {
        $today_time = strtotime(date('Y-m-d'));
        //获取当天要释放的记录
        $list = DB('invite_reward_coin')->where('last_time', '<', $today_time)->where('last_time<end_time')->select();
        foreach ($list as $k => $v) {
            if (date('Y-m-d', $v['last_time']) == date('Y-m-d', ($v['end_time'] - 86400))) {
                continue;
            }
            DB::startTrans();
            try {
                //计算每天释放金币数
                $release_coin = number_format($v['coin'] / $v['release_zq'], 2);
                $userinfo = userinfobyid($v['uid']);
                //修改账户金币数量
                $res = DB('user')->where(['id' => $v['uid']])->setInc('idc', $release_coin);
                if (!$res) {
                    throw new \Exception('账户金币变更失败');
                }
                //添加金币记录
                $log_insert = [
                    'uid' => $v['uid'],
                    'uname' => $v['uname'],
                    'type' => 3,
                    'mqian' => $userinfo['idc'],
                    'money' => $release_coin,
                    'mhou' => $userinfo['idc'] + $release_coin,
                    'note' => '邀请奖励币释放',
                    'oid' => $v['from_uid'],
                    'oname' => $v['from_uname'],
                    'time' => time(),
                ];
                $res1 = DB('logocoin')->insert($log_insert);
                if (!$res1) {
                    throw new \Exception('金币记录添加失败');
                }
                if ($v['last_time']) {
                    $last_time = $v['last_time'] + 84600;
                } else {
                    $last_time = strtotime(date('Y-m-d 23:59:55'));
                }
                $res = DB('invite_reward_coin')->where(['id' => $v['id']])->update(['last_time' => $last_time]);
                if (!$res) {
                    throw new \Exception('邀请奖励记录时间更新失败');
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollback();
                echo "msg :" . $e->getMessage();
            }
        }
        echo "释放完成";
    }

    /**
     * @name 超时未付款取消订单
     * @author zay
     * @Date 2020/3/31 0031 12:08
     */

    public function order_cancel()
    {
        $setting = setting();
        $repay_time = setting('repay_cancel');
        $time = time() - $repay_time * 60;
        $list = Db('ppdd_jiaoyi')->where(['zt' => 1])->where('time', '<', $time)->select();
        foreach ($list as $k => $v) {
            Db::startTrans();
            try {
                //卖家扣币 超过一定次数买家冻结账号
                $cancel_num = Db('ppdd_jiaoyi')->where(['buy_id' => $v['buy_id'], 'zt' => 3, 'is_timeout' => 1])->count();
                //交易取消 求购单取消
                $res = Db('ppdd_jiaoyi')->where(['id' => $v['id'], 'zt' => 1])->update(['zt' => 3, 'update_time' => time(), 'is_timeout' => 1]);
                if (!$res) {
                    throw new \Exception('状态变更失败');
                }
                //取消求购单表
                $res = Db('ppdd')->where(['id' => $v['p_order_id'], 'zt' => 1])->update(['zt' => 3, 'update_time' => time(), 'cancel_time' => time()]);
                if (!$res) {
                    throw new \Exception('求购单状态修改失败');
                }
                //卖家冻结idc解冻
                $res = DB('user')->where(['id' => $v['sell_id']])->setDec('idc_freeze', ($v['num'] + $v['fee']));
                if (!$res) {
                    throw new \Exception('卖家解冻币失败');
                }
                $userinfo = userinfobyid($v['buy_id']);
                $zt = $userinfo['zt'];
                if ($cancel_num >= $setting['qiugou_cancel_num'] - 1) {
                    $zt = 2;
                }
                $res = Db('user')->where(['id' => $v['buy_id']])->update(['idc' => $userinfo['idc'] - $setting['buy_fee'], 'zt' => $zt, 'update_time' => time()]);
                if (!$res) {
                    throw new \Exception('买家未付款处罚扣币失败');
                }
                //
                $log_insert = [
                    'uid' => $v['buy_id'],
                    'uname' => $v['buy_user'],
                    'type' => 9,
                    'mqian' => $userinfo['idc'],
                    'money' => -$setting['buy_fee'],
                    'mhou' => $userinfo['idc'] - $setting['buy_fee'],
                    'note' => '订单超时未付款处罚',
                    'order_id' => $v['id'],
                    'order_sn' => $v['g_order_sn'],
                    'time' => time(),
                ];
                $res = Db('logocoin')->insert($log_insert);
                if (!$res) {
                    throw new \Exception('币使用记录添加失败');
                }
                DB::commit();
                echo "订单号:" . $v['id'] . "取消成功\r\n";
            } catch (\Exception $e) {
                Db::rollback();
                echo "订单号:" . $v['id'] . $e->getMessage() . "\r\n";
            }
        }

    }

    /**
     * @name 超时未放币自动放币
     * @author zay
     * @Date 2020/3/31 0031 12:08
     */

    public function order_complete()
    {
        $setting = setting();
        $repay_time = $setting['send_coin'];
        $time = time() - $repay_time * 60;
        $list = Db('ppdd_jiaoyi')->where(['zt' => 4])->where('update_time', '<', $time)->select();
        foreach ($list as $k => $v) {
            Db::startTrans();
            try {
                //统计卖家超时放币次数
                $sell_timeout_num = Db('ppdd_jiaoyi')->where(['sell_id' => $v['sell_id'], 'zt' => 2, 'is_timeout' => 1])->count();
                //交易成功
                $res = Db('ppdd_jiaoyi')->where(['id' => $v['id'], 'zt' => 4])->update(['zt' => 2, 'update_time' => time(), 'confirm_time' => time(), 'is_timeout' => 1]);
                if (!$res) {
                    throw new \Exception('状态变更失败');
                }
                //求购单表
                $res = Db('ppdd')->where(['id' => $v['p_order_id'], 'zt' => 1])->update(['zt' => 2, 'update_time' => time()]);
                if (!$res) {
                    throw new \Exception('求购单状态修改失败');
                }
                //卖家扣币
                $sell_info = userinfobyid($v['sell_id']);
                $dec_num = $v['num'] + $v['fee'];
                if ($sell_timeout_num >= $setting['sell_timeout_num'] - 1) {
                    $res = DB('user')->where(['id' => $v['sell_id']])->update([
                        'idc_freeze' => $sell_info['idc_freeze'] - $dec_num,
                        'idc' => $sell_info['idc'] - $dec_num,
                        'update_time' => time(),
                        'zt' => 2
                    ]);
                } else {
                    $res = DB('user')->where(['id' => $v['sell_id']])->update([
                        'idc_freeze' => $sell_info['idc_freeze'] - $dec_num,
                        'idc' => $sell_info['idc'] - $dec_num,
                        'update_time' => time()]);
                }
                if (!$res) {
                    throw new \Exception('卖家扣币失败');
                }
                //
                $log_insert = [
                    'uid' => $v['sell_id'],
                    'uname' => $v['sell_user'],
                    'type' => 2,
                    'mqian' => $sell_info['idc'],
                    'money' => -$dec_num,
                    'mhou' => $sell_info['idc'] - $dec_num,
                    'note' => '卖家出售成功',
                    'order_id' => $v['id'],
                    'order_sn' => $v['g_order_sn'],
                    'time' => time(),
                ];
                $res = Db('logocoin')->insert($log_insert);
                if (!$res) {
                    throw new \Exception('币使用记录添加失败');
                }

                //买家账户增加idc
                $userinfo = userinfobyid($v['buy_id']);
                $res = Db('user')->where(['id' => $v['buy_id']])->setInc('idc', $v['num']);
                if (!$res) {
                    throw new \Exception('买家增加币失败');
                }
                //
                $log_insert = [
                    'uid' => $v['buy_id'],
                    'uname' => $v['buy_user'],
                    'type' => 1,
                    'mqian' => $userinfo['idc'],
                    'money' => $v['num'],
                    'mhou' => $userinfo['idc'] + $v['num'],
                    'note' => '买家购买成功',
                    'order_id' => $v['id'],
                    'order_sn' => $v['g_order_sn'],
                    'time' => time(),
                ];
                $res = Db('logocoin')->insert($log_insert);
                if (!$res) {
                    throw new \Exception('币使用记录添加失败');
                }
                DB::commit();
                echo "订单:" . $v['id'] . ' ' . '放币成功';
            } catch (\Exception $e) {
                Db::rollback();
                echo "订单:" . $v['id'] . '   ' . $e;
            }
        }

    }

}